package com.ifast.sys.filter;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.hutool.core.annotation.AnnotationUtil;

public class FormTokenInterceptor extends HandlerInterceptorAdapter {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            FormToken annotation = AnnotationUtil.getAnnotation(((HandlerMethod) handler).getMethod(), FormToken.class);
            if (annotation == null)
            	 return true;
            
            boolean needSaveSession = annotation.save();
            if (needSaveSession) {
                request.getSession(true).setAttribute("token", UUID.randomUUID().toString());
            }
            boolean needRemoveSession = annotation.remove();
            if (needRemoveSession) {
                if (isRepeatSubmit(request)) {
                    log.warn("重复提交,url:"+ request.getServletPath());
                    return false;
                }
                request.getSession(true).removeAttribute("token");
            } 
        } 
        
        return super.preHandle(request, response, handler);
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(true).getAttribute("token");
        if (serverToken == null)
            return true;
        
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) 
            return true;
       
        if (!serverToken.equals(clinetToken)) 
            return true;
        
        return false;
    }
}
